/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Amistades.java
 *
 * Created on 02-sep-2011, 13:54:43
 */
package Ventanas;

import Objetos.PropiedadesIP;
import Proxies.CtrlNotificacionesWS;
import Proxies.CtrlNotificacionesWSService;
import Proxies.CtrlRelojSistemaWSService;
import Proxies.CtrlUsuariosWS;
import Proxies.CtrlUsuariosWSService;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;

/**
 *
 * @author jota
 */
public class Amistades extends javax.swing.JFrame {

    /** Creates new form Amistades */
    CtrlUsuariosWS amista;
    String nomUsuario;

    public Amistades() {
        initComponents();
        PropiedadesIP props = PropiedadesIP.getInstance();
        String IP = props.getServidorCentralIP();
        URL dirUsr = null;
        try {
            dirUsr = new URL(IP + "CtrlUsuarios?wsdl");
        } catch (MalformedURLException ex) {
            Logger.getLogger(Amistades.class.getName()).log(Level.SEVERE, null, ex);
        }
        QName qNaUsr = new QName("http://WebServices/", "CtrlUsuariosWSService");
        amista = new CtrlUsuariosWSService(dirUsr, qNaUsr).getCtrlUsuariosWSPort();
    
        //JFormattedTextField textField1 = new JFormattedTextField (new Integer(3));    
        Object[] fila = new Object[3];
        Iterator<Proxies.DataUsuario> itera = amista.listaUsuarios().getItem().iterator();
        Proxies.DataUsuario usr;
        DefaultTableModel model = (DefaultTableModel) Table_buscarUsr.getModel();
        while (itera.hasNext()) {
            usr = itera.next();
            fila[0] = usr.getNombre();
            fila[1] = usr.getNick();
            fila[2] = usr.getCorreo();
            model.addRow(fila);
        }
        Table_buscarUsr.setRowSelectionInterval(0, 0);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        tUsuarios = new javax.swing.JTable();
        AgregarAmigos = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        tAmigos1 = new javax.swing.JTable();
        quitarAmigos = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        vBuscar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        TextField_BuscarUsuario = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        Table_buscarUsr = new javax.swing.JTable();
        jLabel6 = new javax.swing.JLabel();

        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jTextField1.setText("jTextField1");
        getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 0, 0));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 0, 0));

        tUsuarios.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nombre", "Nick", "Correo"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tUsuarios.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        tUsuarios.getTableHeader().setReorderingAllowed(false);
        jScrollPane2.setViewportView(tUsuarios);
        tUsuarios.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 290, 250, 90));

        AgregarAmigos.setText("<");
        AgregarAmigos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                AgregarAmigosMouseClicked(evt);
            }
        });
        getContentPane().add(AgregarAmigos, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 350, 50, 30));

        tAmigos1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nombre", "Nick", "Correo"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tAmigos1.setColumnSelectionAllowed(true);
        tAmigos1.getTableHeader().setReorderingAllowed(false);
        jScrollPane3.setViewportView(tAmigos1);
        tAmigos1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        getContentPane().add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 290, 250, 90));

        quitarAmigos.setText(">");
        quitarAmigos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                quitarAmigosMouseClicked(evt);
            }
        });
        getContentPane().add(quitarAmigos, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 310, 50, 30));
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 320, -1, -1));
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 220, -1, 10));

        vBuscar.setText("Elegir");
        vBuscar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                vBuscarMouseClicked(evt);
            }
        });
        getContentPane().add(vBuscar, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 130, -1, -1));

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel3.setText("Usuario : ");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 90, -1, -1));

        TextField_BuscarUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                TextField_BuscarUsuarioKeyReleased(evt);
            }
        });
        getContentPane().add(TextField_BuscarUsuario, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 90, 100, -1));

        jLabel4.setFont(new java.awt.Font("Times New Roman", 0, 14));
        jLabel4.setText("Usuarios");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 260, 80, -1));

        jLabel5.setFont(new java.awt.Font("Times New Roman", 0, 14));
        jLabel5.setText("Amigos");
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 260, 80, -1));

        jLabel10.setFont(new java.awt.Font("Times New Roman", 0, 18));
        jLabel10.setText("RED - Agregar/Quitar Amigos");
        getContentPane().add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, -1, -1));

        Table_buscarUsr.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nombre", "Nick", "Correo"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane4.setViewportView(Table_buscarUsr);

        getContentPane().add(jScrollPane4, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 80, 250, 90));
        getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 420, -1, -1));

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
// TODO add your handling code here:
}//GEN-LAST:event_formMouseClicked

private void AgregarAmigosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AgregarAmigosMouseClicked
// TODO add your handling code here:

    int selec[] = tUsuarios.getSelectedRows();
    DefaultTableModel model = (DefaultTableModel) tUsuarios.getModel();
    DefaultTableModel modelA = (DefaultTableModel) tAmigos1.getModel();

    int i = selec.length;
    String nomAmigo;
    Object[] fila = new Object[3];
    
    PropiedadesIP props = PropiedadesIP.getInstance();
    String IP = props.getServidorCentralIP();
    URL dirReloj = null;
    try {
        dirReloj = new URL(IP + "CtrlRelojSistema?wsdl");
    } catch (MalformedURLException ex) {
        Logger.getLogger(Amistades.class.getName()).log(Level.SEVERE, null, ex);
    }
    QName qNaReloj = new QName("http://WebServices/", "CtrlRelojSistemaWSService");
    
    XMLGregorianCalendar fecha = new CtrlRelojSistemaWSService(dirReloj, qNaReloj).getCtrlRelojSistemaWSPort().getTime();
    
    URL dirNotif = null;
    try {
        dirNotif = new URL(IP + "CtrlNotificaciones?wsdl");
    } catch (MalformedURLException ex) {
        Logger.getLogger(Amistades.class.getName()).log(Level.SEVERE, null, ex);
    }
    QName qNaNotif = new QName("http://WebServices/", "CtrlNotificacionesWSService");
    CtrlNotificacionesWS ctrlNotif = new CtrlNotificacionesWSService(dirNotif, qNaNotif).getCtrlNotificacionesWSPort();
    
    String nombreUsuario = amista.getUsuario(nomUsuario).getNombre();

    while (i != 0) {
        nomAmigo = model.getValueAt(selec[i - 1], 2).toString();

        amista.agregarAmigo(nomUsuario, nomAmigo, fecha);
        fila[0] = amista.getUsuario(nomAmigo).getNombre();
        fila[1] = amista.getUsuario(nomAmigo).getNick();
        fila[2] = amista.getUsuario(nomAmigo).getCorreo();
        modelA.addRow(fila);
        String asunto = nombreUsuario+" te agregó como amigo en REDBUCK";
        String mensaje = "<br/><b>"+nombreUsuario+"</b> te ha agregado a su lista de amigos en redbuck.<br/>"
                + "Ingresa a <a href=\"http://localhost:8084/RED/\">RedBuck</a> para conocer mas sobre "+nombreUsuario;
        ctrlNotif.mandarMail(amista.getUsuario(nomAmigo).getCorreo(), asunto, mensaje);

        i--;
    }
    tAmigos1.setModel(modelA);

}//GEN-LAST:event_AgregarAmigosMouseClicked

private void vBuscarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_vBuscarMouseClicked
// TODO add your handling code here:

    if (Table_buscarUsr.getSelectedRow() == -1) {
        nomUsuario = Table_buscarUsr.getValueAt(0, 2).toString();
    } else {
        nomUsuario = Table_buscarUsr.getValueAt(Table_buscarUsr.getSelectedRow(), 2).toString();
    }

    String valido;

    DefaultTableModel tab = (DefaultTableModel) tUsuarios.getModel();
    DefaultTableModel tab2 = (DefaultTableModel) tAmigos1.getModel();
    tab.setRowCount(0);
    tab2.setRowCount(0);

    if (amista.containsKey(nomUsuario)) {

        Iterator<Proxies.DataUsuario> it = amista.listarDAmigos(nomUsuario).getItem().iterator();
        tUsuarios.setModel(tab);
        Proxies.DataUsuario usr;
        Object[] fila = new Object[3];
        Iterator<Proxies.DataUsuario> itera = amista.listaUsuarios().getItem().iterator();
        while (itera.hasNext()) {

            usr = itera.next();
            if (!usr.getCorreo().equals(nomUsuario)) {
                fila[0] = usr.getNombre();
                fila[1] = usr.getNick();
                fila[2] = usr.getCorreo();
                tab.addRow(fila);
            }
        }
        while (it.hasNext()) {
            usr = it.next();
            fila[0] = usr.getNombre();
            fila[1] = usr.getNick();
            fila[2] = usr.getCorreo();
            tab2.addRow(fila);
        }
    } else {
        JOptionPane.showMessageDialog(null, "El Correo no existe");
    }


}//GEN-LAST:event_vBuscarMouseClicked

private void quitarAmigosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_quitarAmigosMouseClicked
// TODO add your handling code here:
    int selec[] = tAmigos1.getSelectedRows();
    ArrayList<String> eleg = new ArrayList<String>();
    DefaultTableModel model = (DefaultTableModel) tUsuarios.getModel();
    DefaultTableModel modelA = (DefaultTableModel) tAmigos1.getModel();

    int i = selec.length;
    String valor;
    Object[] fila = new Object[3];
    while (i != 0) {
        valor = modelA.getValueAt(selec[i - 1], 2).toString();

        amista.quitarAmigo(nomUsuario, valor);
        modelA.removeRow(selec[i - 1]);


        i--;
    }

    tAmigos1.setModel(modelA);


}//GEN-LAST:event_quitarAmigosMouseClicked

private void TextField_BuscarUsuarioKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_TextField_BuscarUsuarioKeyReleased
// TODO add your handling code here:


    TableModel modelo = Table_buscarUsr.getModel();
    final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(modelo);
    Table_buscarUsr.setRowSorter(sorter);
    String text = TextField_BuscarUsuario.getText();
    if (text.length() == 0) {
        sorter.setRowFilter(null);
    } else {
        sorter.setRowFilter(RowFilter.regexFilter(text));

    }



}//GEN-LAST:event_TextField_BuscarUsuarioKeyReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Amistades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Amistades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Amistades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Amistades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Amistades().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AgregarAmigos;
    private javax.swing.JTable Table_buscarUsr;
    private javax.swing.JTextField TextField_BuscarUsuario;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JButton quitarAmigos;
    private javax.swing.JTable tAmigos1;
    private javax.swing.JTable tUsuarios;
    private javax.swing.JButton vBuscar;
    // End of variables declaration//GEN-END:variables
}
